engine = null;
if (window.navigator.appName == "Microsoft Internet Explorer") {
    if (document.documentMode) // IE8
        engine = document.documentMode;
    else // IE 5-7
    {
        engine = 5; //  quirks mode unless proven otherwise
        if (document.compatMode) {
            if (document.compatMode == "CSS1Compat")
                engine = 7; // standards mode
        }
    }
}

//
// Namespace - Module Pattern.
//
var JQD = (function ($, window, document, undefined) {
    // Expose innards of JQD.
    return {
        go: function () {
            for (var i in JQD.init) {
                JQD.init[i]();
            }
        },
        init: {
            frame_breaker: function () {
                if (window.location !== window.top.location) {
                    window.top.location = window.location;
                }
            },
            //
            // Initialize the clock.
            //
            clock: function () {
                if (!$('#clock').length) {
                    return;
                }

                // Date variables.
                var date_obj = new Date();
                var hour = date_obj.getHours();
                var minute = date_obj.getMinutes();
                var day = date_obj.getDate();
                var year = date_obj.getFullYear();
                var suffix = 'AM';

                // Array for weekday.
                var weekday = [
          'Sunday',
          'Monday',
          'Tuesday',
          'Wednesday',
          'Thursday',
          'Friday',
          'Saturday'
        ];

                // Array for month.
                var month = [
          'January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December'
        ];

                // Assign weekday, month, date, year.
                weekday = weekday[date_obj.getDay()];
                month = month[date_obj.getMonth()];

                // AM or PM?
                if (hour >= 12) {
                    suffix = 'PM';
                }

                // Convert to 12-hour.
                if (hour > 12) {
                    hour = hour - 12;
                }
                else if (hour === 0) {
                    // Display 12:XX instead of 0:XX.
                    hour = 12;
                }

                // Leading zero, if needed.
                if (minute < 10) {
                    minute = '0' + minute;
                }

                // Build two HTML strings.
                var clock_time = weekday + ' ' + hour + ':' + minute + ' ' + suffix;
                var clock_date = month + ' ' + day + ', ' + year;

                // Shove in the HTML.
                $('#clock').html(clock_time).attr('title', clock_date);

                // Update every 60 seconds.
                setTimeout(JQD.init.clock, 60000);
            },
            //
            // Initialize the desktop.
            //
            desktop: function () {
                // Cancel mousedown, right-click.
                $(document).mousedown(function (ev) {

                    var tags = ['a', 'button', 'input', 'select', 'textarea', 'tr'];

                    if (!$(ev.target).closest(tags).length) {
                        JQD.util.clear_active();
                        ev.preventDefault();
                        ev.stopPropagation();
                    }
                }).bind('contextmenu', function () {
                    return false;
                });

                // Relative or remote links?
                $('a').live('click', function (ev) {
                    var url = $(this).attr('href');
                    this.blur();

                    if (url.match(/^#/)) {
                        ev.preventDefault();
                        ev.stopPropagation();
                    }
                    else {
                        //$(this).attr('target', '_blank');
                    }
                });

                // Make top menus active.
                $('a.menu_trigger').live('mousedown', function () {
                    if ($(this).next('ul.menu').is(':hidden')) {
                        JQD.util.clear_active();
                        $(this).addClass('active').next('ul.menu').show();
                    }
                    else {
                        JQD.util.clear_active();
                    }
                }).live('mouseenter', function () {
                    // Transfer focus, if already open.
                    if ($('ul.menu').is(':visible')) {
                        JQD.util.clear_active();
                        $(this).addClass('active').next('ul.menu').show();
                    }
                });

                // Desktop icons.
                $('a.icon').live('mousedown', function () {
                    // Highlight the icon.
                    JQD.util.clear_active();
                    $(this).addClass('active');
                }).live('dblclick', function () {
                    var da = $(this).data('dataArr');
                    // Get the link's target.
                    var x = '#' + da.ID;
                    CreateDiv(da);
                    var y = $(x).find('a').attr('href');

                    // Show the taskbar button.
                    if ($(x).is(':hidden')) {
                        $(x).remove().appendTo('#dock');
                        $(x).show('fast');

                        JQD.setRightMore();
                    }

                    // Bring window to front.
                    JQD.util.window_flat();
                    $(y).addClass('window_stack').show();
                }).live('mouseenter', function () {
                    $(this).die('mouseenter').draggable({
                        revert: true,
                        containment: 'parent'
                    });
                });

                // Taskbar buttons.
                $('#dock a').live('click', function () {
                    // Get the link's target.
                    var x = $(this.hash);

                    // Hide, if visible.
                    if (x.is(':visible')) {
                        x.hide();
                    }
                    else {
                        // Bring window to front.
                        JQD.util.window_flat();
                        x.show().addClass('window_stack');
                    }
                });

                // Make windows movable.
                $('div.window_desk').live('mousedown', function () {
                    // Bring window to front.
                    JQD.util.window_flat();
                    $(this).addClass('window_stack');
                }).live('mouseenter', function () {
                    $(this).die('mouseenter').draggable({
                        // Confine to desktop.
                        // Movable via top bar only.
                        cancel: 'a',
                        containment: 'parent',
                        handle: 'div.window_top'
                    }).resizable({
                        containment: 'parent',
                        minWidth: 400,
                        minHeight: 200
                    });

                    // Double-click top bar to resize, ala Windows OS.
                }).find('div.window_top').live('dblclick', function () {
                    JQD.util.window_resize(this);

                    // Double click top bar icon to close, ala Windows OS.
                }).find('img').live('dblclick', function () {
                    // Traverse to the close button, and hide its taskbar button.
                    $($(this).closest('div.window_top').find('a.window_close').attr('href')).hide('fast');

                    // Close the window itself.
                    $(this).closest('div.window_desk').hide();

                    // Stop propagation to window's top bar.
                    return false;
                });

                // Minimize the window.
                $('a.window_min').live('click', function () {
                    $(this).closest('div.window_desk').hide();
                });

                // Maximize or restore the window.
                $('a.window_resize').live('click', function () {
                    JQD.util.window_resize(this);
                    if (engine <= 7)
                        $(this.hash + "_iframe").height($(this.hash + "_page").height());
                });

                // Close the window.
                $('a.window_close').live('click', function () {
                    //                    $(this).closest('div.window').hide();
                    //                    $($(this).attr('href')).hide('fast');
                    $(this).closest('div.window_desk').remove();
                    $(this.hash).remove();
                    JQD.setMore();
                });

                // Show desktop button, ala Windows OS.
                $('#show_desktop').live('mousedown', function () {
                    // If any windows are visible, hide all.
                    if ($('div.window_desk:visible').length) {
                        $('div.window_desk').hide();
                    }
                    else {
                        // Otherwise, reveal hidden windows that are open.
                        $('#dock li:visible a').each(function () {
                            $(this.hash).show();
                        });
                    }
                });

                $('table.data').each(function () {
                    // Add zebra striping, ala Mac OS X.
                    $(this).find('tbody tr:odd').addClass('zebra');
                }).find('tr').live('mousedown', function () {
                    // Clear active state.
                    JQD.util.clear_active();

                    // Highlight row, ala Mac OS X.
                    $(this).closest('tr').addClass('active');
                });
            },
            wallpaper: function () {
                // Add wallpaper last, to prevent blocking.
                if ($('#desktop').length) {
                    $('body').prepend('<img id="wallpaper" class="abs" src="images/gui/desktop.jpg" />');
                }
            }
        },
        util: {
            //
            // Clear active states, hide menus.
            //
            clear_active: function () {
                $('a.active, tr.active').removeClass('active');
                $('ul.menu').hide();
            },
            //
            // Zero out window z-index.
            //
            window_flat: function () {
                $('div.window_desk').removeClass('window_stack');
            },
            //
            // Resize modal window.
            //
            window_resize: function (el) {
                // Nearest parent window.
                var win = $(el).closest('div.window_desk');

                // Is it maximized already?
                if (win.hasClass('window_full')) {
                    // Restore window position.
                    win.removeClass('window_full').css({
                        'top': win.attr('data-t'),
                        'left': win.attr('data-l'),
                        'right': win.attr('data-r'),
                        'bottom': win.attr('data-b'),
                        'width': win.attr('data-w'),
                        'height': win.attr('data-h')
                    });
                }
                else {
                    win.attr({
                        // Save window position.
                        'data-t': win.css('top'),
                        'data-l': win.css('left'),
                        'data-r': win.css('right'),
                        'data-b': win.css('bottom'),
                        'data-w': win.css('width'),
                        'data-h': win.css('height')
                    }).addClass('window_full').css({
                        // Maximize dimensions.
                        'top': '0',
                        'left': '0',
                        'right': '0',
                        'bottom': '0',
                        'width': '100%',
                        'height': '100%'
                    });
                }

                // Bring window to front.
                JQD.util.window_flat();
                win.addClass('window_stack');
            }
        },
        setMore: function () {
            var w = $(window).width() - 300;
            var li_w = 0;
            for (var i = $('#dock li').length - 1; i >= 0; i--) {
                li_w += $($('#dock li')[i]).width();
                if (li_w > w)
                    $($('#dock li')[i]).hide('fast');
                else
                    $($('#dock li')[i]).show('fast');
            }
        },
        setRightMore: function () {
            var w = $(window).width() - 300;
            var li_w = 0;
            var li_bool = false;
            $.each($('#dock li'), function (i, t) {
                li_w += $(t).width();
                if (li_w > w) {
                    li_bool = true;
                    return false;
                }
            });
            if (li_bool) {
                $("#dock li:visible").first().hide('fast');
            }
        },
        format: function (source, params) {
            if (arguments.length == 1)
                return function () {
                    var args = $.makeArray(arguments);
                    args.unshift(source);
                    return $.format.apply(this, args);
                };
            if (arguments.length > 2 && params.constructor != Array) {
                params = $.makeArray(arguments).slice(1);
            }
            if (params.constructor != Array) {
                params = [params];
            }
            $.each(params, function (i, n) {
                source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
            });
            return source;
        }
    };
    // Pass in jQuery.
})(jQuery, this, this.document);

var StartMenu = (function ($, window, document, undefined) {
    return {
        init: function () {
            window.onresize = function () {
                StartMenu.setSize();
            };
            $("#start").click(function () {
                StartMenu.setSize();
                $('#startmenu').css('display', 'inline-block');
                $("#startmenu").slideDown().mouseleave(function () {
                    $('#startmenu').css('display', 'none');
                    $('#links').css('display', 'none');
                });

                $("#desktop").click(function () {
                    $('#startmenu').css('display', 'none');
                });
            });
        },
        setSize: function () {
            //alert($("#programs").height());
            var menu_margin_top = $(window).height() - $("#startmenu").height() - 43;
            $('#startmenu').css("margin-top", menu_margin_top);
            JQD.setMore();
        },
        setLinkClick: function (da) {
            var x = '#' + da.ID;
            CreateDiv(da);
            var y = $(x + "_window");

            if ($(x).is(':hidden')) {
                $(x).remove().appendTo('#dock');
                $(x).show('fast');
                JQD.setRightMore();
            }

            JQD.util.window_flat();
            $(y).addClass('window_stack').show();
        },
        setMenuParent: function (josnStr) {
            if (josnStr.length > 0) {
                StartMenu.createMenuTop(josnStr);
                $.each(josnStr, function (i, t) {
                    var $li = $('<li></li>');
                    var $deska = $('<a href="#"></a>');
                    $deska.append($('<img src="' + t.Image + '" />'));
                    $deska.append(t.Title);
                    $li.append($deska);
                    if (t.Data.length > 0) {
                        $li.click(function () {
                            StartMenu.createMenuChild(t.Data);
                        });
                    }
                    $('#programs').append($li);
                });
            }
        },
        createMenuChild: function (josnStr) {
            if (josnStr) {
                $('#links li').remove();
                $.each(josnStr, function (i, t) {
                    var $li = $('<li></li>');
                    var $a = $('<a href="#"></a>');
                    $a.append($('<span>' + t.Title + '</span>'));
                    $a.click(function () {
                        StartMenu.setLinkClick(t);
                    });
                    $li.append($a);
                    $('#links').append($li);
                });
                $('#links').css('display', 'block');
                if ($('#links').height() > $('programs').height()) {
                    StartMenu.setSize();
                }
            }
        },
        createMenuTop: function (josnStr) {
            if (josnStr) {
                $.each(josnStr, function (i, t) {
                    var $ul_parent = $('<ul></ul>');
                    var $li_parent = $('<li></li>');
                    $li_parent.append('<a class="menu_trigger" href="#">' + t.Title + '</a>');
                    if (t.Data.length > 0) {
                        var $ul_child = $('<ul class="menu"></ul>');
                        $.each(t.Data, function (ii, tt) {
                            var $li_child = $('<li></li>');
                            var $a = $('<a href="#"></a>');
                            $a.append(tt.Title);
                            $a.click(function () {
                                StartMenu.setLinkClick(tt);
                                JQD.util.clear_active();
                            });
                            $li_child.append($a);

                            $ul_child.append($li_child);
                        });
                        $li_parent.append($ul_child);
                    }
                    $ul_parent.append($li_parent);

                    $('#bar_top').append($ul_parent);
                });
            }
        }
    };
})(jQuery, this, this.document);

//
// Kick things off.
//
jQuery(document).ready(function () {
    JQD.go();

    StartMenu.init();
});

var win_top = 30;
var win_left = 120;
function CreateDiv(data) {
    if ($('#' + data.ID).length > 0) {
        //var page = "#" + data.ID + "_page";
        //$(page).load(data.Path);
        return;
    }
    var li = $(JQD.format(LiString, data.ID, data.Medium, data.Title));
    $('#dock').append(li);
    var div = $(JQD.format(DivString, data.ID, data.Small, data.Title));
    $(div).css({ top: win_top + 'px', left: win_left + 'px' });
    $('#wrapper').append(div);
    var page = "#" + data.ID + "_page";
    var $iframe = $('<iframe id="' + data.ID + '_iframe" frameborder="no" border="0" scrolling="auto" width="100%" height="100%"></iframe>');
    $iframe.attr('src', data.Path);
    $(page).append($iframe);
    //$(page).load(data.Path);

    if ((win_top + 70 + 500) > $(window).height() || (win_left + 700) > $(window).width()) {
        win_top = 30;
        win_left += 35;
    }
    else {
        win_top += 25;
        win_left += 25;
    }
    if (engine <= 7)
        $iframe.height($(div).height() - 35);
}

var margin_left = 80;
var margin_top = 90;

function CreateDesktopIcon(josnstr) {
    if (josnstr.length >= 1) {
        var topNum = 20;
        var leftNum = 20;
        var h = $(document).height();
        var w = $(document).width();
        //alert(h);
        $.each(josnstr, function (i, t) {
            if (w < leftNum) return;
            if (h < (topNum + 150)) {
                leftNum += (margin_left + 20);
                topNum = 20;
            }

            var $deska = $('<a href="#"></a>');
            $deska.addClass('abs icon');
            $deska.css({ top: topNum + 'px', left: leftNum + 'px' });
            $deska.attr('id', 'a_' + t.ID);
            $deska.append($('<img src="' + t.Large + '" />'));
            $deska.append(t.Title);
            $deska.data('dataArr', t);
            $('#desktop').append($deska);

            topNum += (margin_top + 20);
        });
    }
}

var DivString = '<div id="{0}_window" class="abs window_desk"><div class="abs window_inner">' +
'<div class="window_top"><span class="float_left"><img src="{1}" />{2}</span>' +
'<span class="float_right"><a href="#" class="window_min"></a><a href="#{0}" class="window_resize"></a>' +
'<a href="#{0}" class="window_close"></a></span></div></div><div id="{0}_page" class="abs window_content"></div>' +
'<span class="abs ui-resizable-handle ui-resizable-se"></span></div>';

var LiString = '<li id="{0}"><a href="#{0}_window"><img src="{1}" />{2}</a></li>';